﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using DevExpress.Xpo;
using DevExpress.ExpressApp.Security;
using System.Security.Permissions;
using DevExpress.ExpressApp.Editors;
using DevExpress.Persistent.Base;
using DevExpress.Persistent.Base.Security;
using DevExpress.ExpressApp.Filtering;
using DevExpress.Data.Filtering.Helpers;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Utils;

namespace CRMSolution.Module
{
    [NonPersistent]
    public class ActionAccessPermission : PermissionBase
    {
        public ActionAccessPermission()
        {

        }

        public ActionAccessPermission(string actionId, ActionAccessModifier modifier)
        {
            this.ActionId = actionId;
            this.Modifier = modifier;
        }

        public string ActionId { get; set; }
        public ActionAccessModifier Modifier { get; set; }

        public override System.Security.IPermission Copy()
        {
            return new ActionAccessPermission(ActionId, Modifier);
        }

        public override string ToString()
        {
            EnumDescriptor enumDescriptor = new EnumDescriptor(typeof(ActionAccessModifier));
            return String.Format("{0} {1} ({2})", CaptionHelper.GetClassCaption(GetType().FullName), ActionId, enumDescriptor.GetCaption(Modifier));
        }

        public override void FromXml(SecurityElement e)
        {
            ActionId = e.Attributes["actionId"].ToString();
            Modifier = (ActionAccessModifier)Enum.Parse(typeof(ActionAccessModifier), e.Attributes["modifier"].ToString());
        }

        public override SecurityElement ToXml()
        {
            SecurityElement result = base.ToXml();
            result.AddAttribute("actionId", ActionId);
            result.AddAttribute("modifier", Modifier.ToString());
            return result;
        }

        public override bool IsSubsetOf(System.Security.IPermission target)
        {
            if (base.Intersect(target) != null)
            {
                if (((ActionAccessPermission)target).ActionId == this.ActionId
                    && ((ActionAccessPermission)target).Modifier == this.Modifier)
                {
                    return true;
                }
                return false;
            }
            return false;
        }
    }
    public enum ActionAccessModifier
    {
        None,
        Allow,
        Deny
    }
}
